import { apiClient } from './axios'

// 权限相关接口
export interface Permission {
  id: number
  name: string
  code: string
  module: string
  module_display?: string
  description?: string
  is_active: boolean
  created_at: string
  updated_at: string
}

// 角色权限关联
export interface RolePermission {
  id: number
  role: string
  permission_id: number
  is_granted: boolean
  created_at: string
  permission?: Permission
}

// 用户权限
export interface UserPermission {
  id: number
  user_id: number
  permission_id: number
  is_granted: boolean
  granted_by?: number
  granted_at: string
  expires_at?: string
  permission?: Permission
}

export const permissionsApi = {
  // 获取所有权限
  getPermissions: () => {
    return apiClient.get<Permission[]>('/permissions')
  },

  // 获取权限详情
  getPermission: (id: number) => {
    return apiClient.get<Permission>(`/permissions/${id}`)
  },

  // 创建权限
  createPermission: (data: Omit<Permission, 'id' | 'created_at' | 'updated_at'>) => {
    return apiClient.post<Permission>('/permissions', data)
  },

  // 更新权限
  updatePermission: (id: number, data: Partial<Permission>) => {
    return apiClient.put<Permission>(`/permissions/${id}`, data)
  },

  // 删除权限
  deletePermission: (id: number) => {
    return apiClient.delete(`/permissions/${id}`)
  },

  // 获取角色权限
  getRolePermissions: (role?: string) => {
    const params = role ? { role } : {}
    return apiClient.get<RolePermission[]>('/permissions/role-permissions', { params })
  },

  // 设置角色权限
  setRolePermission: (data: { role: string; permission_id: number; is_granted: boolean }) => {
    return apiClient.post<RolePermission>('/permissions/role-permissions', data)
  },

  // 批量设置角色权限
  batchSetRolePermissions: (data: { role: string; permissions: Array<{ permission_id: number; is_granted: boolean }> }) => {
    return apiClient.post('/permissions/role-permissions/batch', data)
  },

  // 获取用户权限
  getUserPermissions: (userId: number) => {
    return apiClient.get<UserPermission[]>(`/permissions/users/${userId}/permissions`)
  },

  // 设置用户权限
  setUserPermission: (data: { user_id: number; permission_ids: number[] }) => {
    return apiClient.post(`/permissions/users/${data.user_id}/permissions`, { permission_ids: data.permission_ids })
  },

  // 删除用户特殊权限
  removeUserPermission: (userId: number, permissionId: number) => {
    return apiClient.delete(`/permissions/users/${userId}/permissions/${permissionId}`)
  },

  // 获取用户有效权限（包括角色权限和用户权限）
  getUserEffectivePermissions: (userId: number) => {
    // 使用获取用户权限接口，它返回的就是有效权限
    return apiClient.get<Permission[]>(`/permissions/users/${userId}/permissions`)
  },

  // 检查用户权限
  checkUserPermission: (userId: number, permissionCodes: string[]) => {
    return apiClient.post<{ user_id: number; permissions: Record<string, boolean> }>(`/permissions/users/${userId}/check`, {
      permission_codes: permissionCodes
    })
  }
};